#include "Socket.hpp"
#include <memory>
#include <sys/wait.h>
#include <functional>

using namespace SocketModule;
using ioserve_t=std::function<void(std::shared_ptr<Socket>& sock,InetAddr&client)>;

class TCPServe
{
public:
    TCPServe(uint16_t port)
        :_port(port),
         _isrunning(false),
         _listensockfd(std::make_unique<TCPSocket>(_port))        
    {
        _listensockfd->BuildTCPSocketfd(_port);
    }
    void Start(ioserve_t callback)
    {
        _isrunning=true;
        while(_isrunning)
        {
            InetAddr client;
            auto newsock = _listensockfd->AcceptSocket(&client);//获取连接和client
            if(newsock==nullptr)
            {
                continue;
            }
            LOG(DEBUG)<<"accept success";
            pid_t id=fork();
            if(id<0)
            {
                LOG(FATAL)<<"fork unsuccess";
                exit(FORK_ERR);
            }
            else if(id==0)
            {
                //子进程
                _listensockfd->Close();
                if(fork()>0)
                    exit(OK);
                callback(newsock,client);
                newsock->Close();
                exit(OK);
            }
            else
            {
                newsock->Close();
                pid_t rid = ::waitpid(id,nullptr,0);
                (void)rid;
            }
        }
        _isrunning=false;
    }
private:
    uint16_t _port;
    bool _isrunning;
    std::unique_ptr<TCPSocket> _listensockfd;
    // ioserve_t _service;
};